import React, { useState, useCallback } from 'react';
import { FlatList, ActivityIndicator, RefreshControl, View, Text, StyleSheet } from 'react-native';
import NomoreComponent from "@/components/NomoreComponent";
import Empty from "@/components/empty";

const CustomFlatList = ({
                            data,
                            renderItem,
                            keyExtractor,
                            onRefresh,
                            onLoadMore,
                            refreshing = false,
                            loadingMore = false,
                            totalPages,
                            totalCount,
                            currentPage,
                            ListEmptyComponent = <Empty title={"暂无数据~"} />,
                            ListFooterComponent,
                        }) => {
    const handleLoadMore = () => {
        if (!loadingMore && onLoadMore) {
            onLoadMore();
        }
    };

    return (
        <FlatList
            data={data}
            renderItem={renderItem}
            keyExtractor={keyExtractor}
            refreshControl={
                <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
            }
            ListEmptyComponent={ListEmptyComponent}
            ListFooterComponent={
                loadingMore ? (
                    <View style={styles.footer}>
                        <ActivityIndicator size="small" color="#666" />
                    </View>
                ) : (
                    (data.length >= totalCount && data.length > 0) || (currentPage >= totalPages && data.length > 0) ? (
                       <NomoreComponent/>
                    ) : (
                        ListFooterComponent
                    )
                )
            }

            onEndReachedThreshold={0.1} // 到达底部时触发的阈值
            onEndReached={handleLoadMore}
            style={{ height: '100%' }}
            showsVerticalScrollIndicator={false}
        />
    );
};

const styles = StyleSheet.create({
    footer: {
        padding: 10,
        justifyContent: 'center',
        alignItems: 'center',
    },
    emptyText: {
        textAlign: 'center',
        marginTop: 20,
        color: '#666',
    },
    noMoreText: {
        textAlign: 'center',
        padding: 10,
        color: '#666',
    },
});

export default CustomFlatList;
